package com.ys.service.mall.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ys.entity.mall.TmGiftUse;
import com.ys.entity.mall.TmGift;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.mall.TmGiftEnum;
import com.ys.mapper.mall.TmGiftUseMapper;
import com.ys.mapper.mall.TmGiftMapper;
import com.ys.service.flow.YspTaskService;
import com.ys.service.mall.TmGiftUseService;
import com.ys.vo.Flow;
import com.ys.vo.R;

@Service("tmGiftUseService")
public class TmGiftUseServiceImpl implements TmGiftUseService {
	@Autowired
	private TmGiftMapper tmGiftMapper;
	@Autowired
	private TmGiftUseMapper tmGiftUseMapper;
	@Autowired
	private YspTaskService yspTaskService;

	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {
		
		TmGiftUse entity = new TmGiftUse().setId(id).queryFirst();
		String bid = entity.getBid();
		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				if (f.getState() == Flow.State.FINISH.value) {
					flowFinish(id);
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	@Transactional
	public void flowFinish(Long id) throws Exception {
		
		TmGiftUse entity = new TmGiftUse().setId(id).queryFirst();
		
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		tmGiftUseMapper.update(entity);
		
		// 用户礼品更新
		TmGift tmGift = new TmGift().setCode(entity.getGiftCode()).queryFirst();
		tmGift.setState(TmGiftEnum.State.DISABLE.value);
		tmGiftMapper.update(tmGift);
	}

	@Override
	@Transactional
	public R delete(Long id) throws Exception {
		
		TmGiftUse entity = new TmGiftUse().setId(id).queryFirst();
		if (entity == null) {
			return R.error("数据不存在");
		} else if (entity.getEffectStock() != FlowEnum.EffectStock.NOT_EFFECT.value) {
			return R.error("非未生效数据，无法删除");
		}
		
		tmGiftUseMapper.deleteTrue(id);
		
		// 用户礼品恢复
		TmGift tmGift = new TmGift().setCode(entity.getGiftCode()).queryFirst();
		tmGift.setState(TmGiftEnum.State.ABLE.value);
		tmGiftMapper.update(tmGift);
		return R.ok();
	}
	
}
